using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using HtmlAgilityPack;

namespace libRDS
{
    public class TreasuryDirect
    {
        public string FindCusip(DateTime dtMaturity, double dCoupon)
        {
            string sMMM = dtMaturity.ToString("MMM");
            string sURL =  "http://www.savingsbonds.gov/RI/OFAuctions?"+
                            "typesec=all&searchtype=maturity&form=new&" +
                            "begMon={0}&begDay={1}&begYr={2}&endMon={0}&endDay={1}&endYr={2}";
            sURL = string.Format(sURL, sMMM, dtMaturity.Day, dtMaturity.Year);
            HtmlWeb hw = new HtmlWeb();
            //hw.Proxy = "http://gcm-ct-prod-pac.gcm.com:3128";
            HtmlDocument doc = hw.Load(sURL);
            HtmlNodeCollection divs = doc.DocumentNode.SelectNodes("//div");
            HtmlNodeCollection tbls = divs[12].SelectNodes("//table");
            HtmlNodeCollection rows = tbls[0].SelectNodes(".//tr");
            for (int nRow = 1; nRow < rows.Count; nRow++)
            {
                HtmlNodeCollection cols = rows[nRow].SelectNodes(".//td");
                double dInterestRate = double.Parse(cols[7].InnerText.Trim());
                if (fnCompareCoupon(dCoupon,dInterestRate)) return cols[10].InnerText.Trim();
            }
            return string.Empty;
        }
        bool fnCompareCoupon(double dReal, double dRound)
        {
            if (dReal == dRound) return true;
            //if (dReal < 8) return dReal == dRound;
            double dRealR = Math.Floor(dReal * 100 + 0.1) / 100;
            double dRoundR = Math.Floor(dRound * 100 +0.1) / 100;
            return dRealR == dRoundR;
        }

        public Dictionary<string, object> GetSecInfoByCusip(string sCusip)
        {
            Dictionary<string, object> ret = new Dictionary<string, object>();
            string sURL = "http://www.treasurydirect.gov/RI/OFAuctions?typesec=all&searchtype=cusip&form=new&cusip={0}";
            sURL = string.Format(sURL, sCusip);

            HtmlWeb hw = new HtmlWeb();
            //hw.Proxy = "http://gcm-ct-prod-pac.gcm.com:3128";
            //hw.Proxy = sProxy;
            HtmlDocument doc = hw.Load(sURL);
            HtmlNode content = doc.GetElementbyId("content");
            HtmlNodeCollection divs = content.SelectNodes(".//div");

            foreach (HtmlNode div in divs)
            {
                if (div.Attributes["class"].Value.Equals("secinfo"))
                {
                    fnHandleCusipInfo(div, ret);
                    HtmlNodeCollection tbls = div.SelectNodes("//table");
                    fnHandleIssueInfo(tbls[0], ret);
                    fnHandleAuctInfo(tbls[1], ret);
                    HtmlNodeCollection rows = tbls[0].SelectNodes(".//tr");
                }
            }
            return ret;
        }

        bool fnHandleCusipInfo(HtmlNode div, Dictionary<string, object> ret)
        {
            HtmlNodeCollection items = div.SelectNodes(".//ul/li/ul/li");
            string sCpn = items[0].InnerText.Trim();
            ret["Coupon"] = double.Parse(sCpn.Replace("%", ""));
            string sTerms = items[1].InnerText.Trim();
            string[] ssTerms = sTerms.Split(',');
            string[] ssYear = ssTerms[0].Trim().Split('-');
            string[] ssMonth = ssTerms[1].Trim().Split('-');
            ret["YrTerm"] = int.Parse(ssYear[0].Trim());
            ret["MnTerm"] = int.Parse(ssMonth[0].Trim());
            return true;
        }

        bool fnHandleIssueInfo(HtmlNode tbl, Dictionary<string, object> ret)
        {
            HtmlNodeCollection rows = tbl.SelectNodes(".//tr");
            HtmlNodeCollection cols = rows[0].SelectNodes(".//td");
            ret["SecType"] = cols[1].InnerText.Trim();
            ret["FistCpnDate"] = DateTime.Parse(cols[4].InnerText.Trim().Replace('-', '/'));
            cols = rows[1].SelectNodes(".//td");
            ret["Series"] = cols[1].InnerText.Trim();
            ret["StandardInterestPayment"] = double.Parse(cols[4].InnerText.Trim());
            cols = rows[3].SelectNodes(".//td");
            ret["HighYield"] = double.Parse(cols[1].InnerText.Trim());
            ret["HighPrice"] = double.Parse(cols[2].InnerText.Trim());
            cols = rows[4].SelectNodes(".//td");
            ret["AvgMedianYield"] = double.Parse(cols[1].InnerText.Trim());
            ret["AvgMedianPrice"] = double.Parse(cols[2].InnerText.Trim());
            cols = rows[5].SelectNodes(".//td");
            ret["LowYield"] = double.Parse(cols[1].InnerText.Trim());
            ret["LowPrice"] = double.Parse(cols[2].InnerText.Trim());
            return true;
        }

        bool fnHandleAuctInfo(HtmlNode tbl, Dictionary<string, object> ret)
        {
            HtmlNodeCollection rows = tbl.SelectNodes(".//tr");
            HtmlNodeCollection cols = rows[0].SelectNodes(".//td");
            ret["AllocationAtTheHigh"] = double.Parse(cols[1].InnerText.Trim().Replace("%", ""));
            cols = rows[1].SelectNodes(".//td");
            ret["OfferingAmt"] = double.Parse(cols[1].InnerText.Trim().Replace("billion", "").Trim());
            ret["AnnounceDate"] = DateTime.Parse(cols[4].InnerText.Trim().Replace('-', '/'));
            cols = rows[2].SelectNodes(".//td");
            ret["AuctionDate"] = DateTime.Parse(cols[1].InnerText.Trim().Replace('-', '/'));
            ret["IssueDate"] = DateTime.Parse(cols[4].InnerText.Trim().Replace('-', '/'));
            cols = rows[3].SelectNodes(".//td");
            ret["MaturityDate"] = DateTime.Parse(cols[1].InnerText.Trim().Replace('-', '/'));
            string sD = cols[4].InnerText.Trim();
            if (sD == "n/a") ret["OriginalIssueDate"] = DateTime.MinValue;
            else  ret["OriginalIssueDate"] = DateTime.Parse(cols[4].InnerText.Trim().Replace('-', '/'));
            cols = rows[5].SelectNodes(".//td");
            ret["TotalTendered"] = double.Parse(cols[1].InnerText.Trim().Replace(",", "").Replace("$", ""));
            ret["TotalAccepted"] = double.Parse(cols[4].InnerText.Trim().Replace(",", "").Replace("$", ""));
            return true;
        }
    }
}
